﻿namespace Pub.Class
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public static class WebControlExtensions
    {
        public static string Eval<TEntity>(this Page page, Func<TEntity, string> func)
        {
            return func((TEntity) page.GetDataItem()).ToStr();
        }

        public static TResult Eval<TEntity, TResult>(this Page page, Func<TEntity, TResult> func)
        {
            return func((TEntity) page.GetDataItem());
        }

        public static string GetControlValue(this Page page, string ctrlID)
        {
            Control control = page.FindControl(ctrlID);
            if (control is TextBox)
            {
                return ((TextBox) control).Text;
            }
            if (control is DropDownList)
            {
                return ((DropDownList) control).SelectedItem.Value;
            }
            return "";
        }

        public static void HoverScript(this DataGrid dg, string color, string hoverColor)
        {
            for (int i = 0; i < dg.Items.Count; i++)
            {
                if ((dg.Items[i].ItemType.ToString() == "Item") || (dg.Items[i].ItemType.ToString() == "AlternatingItem"))
                {
                    TableRow parent = (TableRow) dg.Items[i].Cells[0].Parent;
                    Js.AddAttr(parent, "onmouseover", "this.bgColor='" + hoverColor + "'");
                    Js.AddAttr(parent, "onmouseout", "this.bgColor='" + color + "'");
                }
            }
        }

        public static void HoverScript(this GridView dv, string color, string hoverColor)
        {
            for (int i = 0; i < dv.Rows.Count; i++)
            {
                if (dv.Rows[i].RowType.ToString() == "DataRow")
                {
                    TableRow parent = (TableRow) dv.Rows[i].Cells[0].Parent;
                    Js.AddAttr(parent, "onmouseover", "gvBgColor = this.bgColor; this.bgColor='" + hoverColor + "'");
                    Js.AddAttr(parent, "onmouseout", "this.bgColor=" + ((color == "") ? "gvBgColor;" : ("'" + color + "'")));
                }
            }
        }

        public static void SetControlValue(this Page page, string ctrlID, string value)
        {
            Control control = page.FindControl(ctrlID);
            if (control is TextBox)
            {
                ((TextBox) control).Text = value;
            }
            if (control is DropDownList)
            {
                DropDownList list = (DropDownList) control;
                foreach (ListItem item in list.Items)
                {
                    if (item.Value == value)
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }
        }
    }
}

